package com.elite.groovy.callback


import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject

//import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest
//import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

//import org.springframework.http.MediaType

//import okhttp3.MediaType.Companion.toMediaType

public class apiAutoGetU9ItemCategoryList implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiAutoGetU9ItemCategoryList.class);
    String v_starttime = '';
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
      /*
         获取U9获取商品分类列表(商品类别) -- demi
           防止 定时任务同一时间 多次执行
           设计最大执行时间范围 开始执行后立即更新下次允许执行时间 在此期间 禁止重复执行
          1、执行频率：每日凌晨 0点
          2、根据账号和密码 获取token
      */

        String sql0 = """
            select    case when  now() >next_executedate   then  1 else 0 end  as flag from  interface_lock where interfaceName = 'apiAutoGetU9ItemCategoryList'
        """;
        // 查询是否有已经在执行的定时任务或者 或者之前的上次定时任务异常结束
        int flag = eliteBean.chaxun_sql(sql0, "dataSource").get(0).get("flag");

        log.debug("flag: ", flag);

        if (flag == 0) {
            log.debug(" apiAutoGetU9ItemCategoryList 获取U9获取商品分类列表(商品类别)： 未到下次执行时间 不予执行");
            return "success";
        } else {
            // 立即数据库标记正在执行  频率内不重复执行
            eliteBean.update("update interface_lock set last_executedate = now(),next_executedate =STR_TO_DATE( date_add(now(), interval frequency*60 second),'%Y-%m-%d %H:%i:%s') where interfaceName = 'apiAutoGetU9ItemCategoryList'", "dataSource");
        };

        log.warn("---apiAutoGetU9ItemCategoryList 开始---");

        Date date1 = new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        v_starttime = sdf.format(date1);
        log.debug(" 开始时间"+v_starttime);

        int timeout = 30000;
        int enableSSLflag = 0;

        String charset = "utf-8";
        Map<String, Object> headMap = new HashMap<>(); // 请求参数头
        headMap.put("Content-Type", "application/json;charset=UTF-8");


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");


        try {

            // 获取token
            String querySQL1 = "select string3 as token from sysc_interface where method='getU9Token' ";
            String token = eliteBean.chaxun_sql(querySQL1, "dataSource").get(0).get("token");

            log.debug("当前token：" + token);
            headMap.put("Authorization", "Bearer " + token);
            // 获取接口地址
            String querySQL2 = "select url  from sysc_interface where method='GetU9ItemCategoryList' ";
            String url = eliteBean.chaxun_sql(querySQL2, "dataSource").get(0).get("url");

            String requestBody = url + 'code=';
            log.debug("apiAutoGetU9ItemCategoryList--------requestBody:" + requestBody);
            String responseInfo = Util.doHttpGetUseHead(requestBody, charset, timeout, enableSSLflag, headMap);

            log.debug("apiAutoGetU9ItemCategoryList--------responseInfo:" + responseInfo);
            JSONArray resArr = JSONArray.fromObject(responseInfo);

            // 数据 备份 再删除
            String[] arr =new String[2];

            // 差 2句 sql

            arr[0] = "insert into ItemCategoryList_log(log_guid,list_guid,code,name,status,ItemCategoryList_createddate,createddate)" +
                    "select uuid(),list_guid,code,name,status,createddate,now()  from ItemCategoryList";
            arr[1] = "delete  from  ItemCategoryList where 1=1";

           // ItemCategoryList_log
            int[]  result=eliteBean.updateBatch(arr,'dataSource');

            log.debug("U9商品分类列表数据备份结果："+result.toString());

            saveU9ItemCategoryList(eliteBean, resArr);

            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('1','apiAutoGetU9ItemCategoryList','1', STR_TO_DATE('"+v_starttime+"' ,'%Y/%m/%d %H:%i:%s')  ,now(),'执行成功','','') ";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");

        } catch (Exception e) {

            log.error("获取U9获取商品分类列表(商品类别)异常", Util.getERRO(e));
            def v_parameter2;
            def v_length= Util.getERRO(e).toString().length();
            log.debug("v_length: ",v_length);
            if( v_length>2500)  {
                v_parameter2 =Util.getERRO(e).substring(0, 2500).replace("'", "\\");
            }

            if( v_length<=2500 && v_length>0)  {
                v_parameter2 =Util.getERRO(e).substring(0, v_length-1).replace("'", "\\");
            }
            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('-1','apiAutoGetU9ItemCategoryList','1',STR_TO_DATE('"+v_starttime +"', '%Y/%m/%d %H:%i:%s') ,now(),'接口异常2','','"+v_parameter2+"')";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");

        };

        log.debug("获取U9获取商品分类列表(商品类别) 耗时：" + ((long) new Date().getTime() - (long) date1.getTime()) + "毫秒");

        return "success";
    };

    public String saveU9ItemCategoryList(EliteBean eliteBean, JSONArray resArr) {

        try {

            if (resArr.size() > 0) {
                String sql = '';
                // 解析接口 保存数据
                for (int i = 0; i < resArr.size(); i++) {
                    String code = resArr[i].code;
                    String name = resArr[i].name;
                    if(!code){
                        code = '';
                    };
                    if(!name){
                        name = '';
                    };
                    sql = "insert into ItemCategoryList(list_guid,code,name,status,createddate) values(  uuid(),'" + code + "','" + name + "','1',now())";
                    int res = eliteBean.update(sql, "dataSource");
                    int num = i + 1;
                    log.debug("获取U9获取商品分类列表(商品类别) 保存第" + num + "次结果: " + res);

                };
            };
        } catch (Exception e) {

            log.error("保存U9获取商品分类列表(商品类别)异常", Util.getERRO(e));

            def v_parameter2;
            def v_length= Util.getERRO(e).toString().length();
            log.debug("v_length: ",v_length);
            if( v_length>2500)  {
                v_parameter2 =Util.getERRO(e).substring(0, 2500).replace("'", "\\");
            }

            if( v_length<=2500 && v_length>0)  {
                v_parameter2 =Util.getERRO(e).substring(0, v_length-1).replace("'", "\\");
            }
            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('-1','apiAutoGetU9ItemCategoryList','1',STR_TO_DATE('"+v_starttime +"', '%Y/%m/%d %H:%i:%s') ,now(),'接口异常1','','"+v_parameter2+"')";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");
        }


    }

}
